package com.watson.fragment;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ViewFlipper;

import androidx.annotation.Nullable;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.watson.BaseFrag;
import com.watson.LoginActivity;
import com.watson.R;
import com.watson.activity.EnterActivity;
import com.watson.activity.InspectionActivity;
import com.watson.activity.OutActivity;
import com.watson.activity.QuestActivity;
import com.watson.activity.RecognizeActivity;
import com.watson.activity.TaskActivity;
import com.watson.adapter.ModuleAdapter;
import com.watson.adapter.SourceZAdapter;
import com.watson.bean.ChooseBean;
import com.watson.http.CommonHttpConsts;
import com.watson.http.HttpCallbackData;
import com.watson.http.HttpClient;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;
import com.watson.utils.StringUtils;
import com.watson.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Map;

public class HomeFragment extends BaseFrag {
    private LinearLayout lyChu, lyQuest, lyRecords;
    private TextView tvQuestNum, tvChuNum, tvOutNum, tvUserName, tvchu, tvtask, tvdai, tvchu1, tvtask1, tvdai1;
    private RecyclerView recyclerModule;
    private ModuleAdapter moduleAdapter;
    private ArrayList<Map> moduleBeans;
    public static String U_DEPOT_ID = "";
    public static String U_DEPOT_NAME = "";
    private ArrayList<Map> warehouse;
    public ViewFlipper viewFlipper;
    private GestureDetectorCompat detectorCompat;

    @Override
    protected View initContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

    private void initData() {
        stateList = new ArrayList<>();
        warehouse = new ArrayList<>();
        String warehouseStr = SPUtils.get(mContext, "warehouse", "") + "";
        if (!StringUtils.isEmpty(warehouseStr)) {
            warehouse = (ArrayList<Map>) JSON.parseArray(SPUtils.get(mContext, "warehouse", "") + "", Map.class);
        }

        for (int i = 0; i < warehouse.size(); i++) {
            ChooseBean chooseBean = new ChooseBean();
            chooseBean.setId(i);
            chooseBean.setUid(warehouse.get(i).get("U_DEPOT_ID") + "");
            chooseBean.setName(warehouse.get(i).get("U_DEPOT_NAME") + "");
            chooseBean.setFIFO(Boolean.valueOf(warehouse.get(i).get("isFIFO") + ""));
            chooseBean.setVerification(Boolean.valueOf(warehouse.get(i).get("isVerification") + ""));
            stateList.add(chooseBean);
        }

        if (stateList.size() > 0) {
            stateList.get(0).setType(0);
            tvUserName.setText(stateList.get(0).getName());
            U_DEPOT_ID = stateList.get(0).getName();
            U_DEPOT_NAME = stateList.get(0).getUid();
            SPUtils.put(mContext, "isFIFO", stateList.get(0).isFIFO());
            SPUtils.put(mContext, "isVerification", stateList.get(0).isVerification());
//            Get_WMS_HomeStatistics();
        }
    }

    public void setDataView(Map dataMap) {
        tvchu.setText(dataMap.get("sumoutquantity") + "/" + dataMap.get("sumpayablequantity"));
        tvtask.setText(dataMap.get("outquantity") + "/" + dataMap.get("payablequantity"));
        tvdai.setText(dataMap.get("billquntity") + "");
        tvOutNum.setVisibility(View.INVISIBLE);
        tvChuNum.setVisibility(View.INVISIBLE);
        tvQuestNum.setVisibility(View.INVISIBLE);
        ArrayList<Map> cornermark = new ArrayList<>();
        cornermark = (ArrayList<Map>) JSON.parseArray(dataMap.get("cornermark") + "", Map.class);
        if (cornermark.size() > 0) {
            moduleAdapter.cornermark(cornermark);
        }
    }

    public void setDataView2(Map dataMap) {
//        "Input_unclaimed": 0,//待领取验单任务数量
//        "Input_billquntity": 4,//应验单任务数量
//        "Input_includedquantity": 7,//个人应验单任务
//        "Input_quantity": 7,//个人已验单
//        "Input_sumincludedquantity": 7,//总应验单
//        "Input_suminputquantity": 0//总已验单数量

        tvchu1.setText(dataMap.get("Input_suminputquantity") + "/" + dataMap.get("Input_sumincludedquantity"));
        tvtask1.setText(dataMap.get("Input_quantity") + "/" + dataMap.get("Input_includedquantity"));
        tvdai1.setText(dataMap.get("Input_unclaimed") + "");
        ArrayList<Map> cornermark = new ArrayList<>();
        cornermark = (ArrayList<Map>) JSON.parseArray(dataMap.get("Input_cornermark") + "", Map.class);
        if (cornermark.size() > 0) {
            moduleAdapter.cornermark1(cornermark);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.e("TAG", "requestCode:" + requestCode);
        LogUtils.e("TAG", "resultCode:" + resultCode);

    }

    @Override
    public void onResume() {
        super.onResume();
        Get_WMS_HomeStatistics();
        new Handler(Looper.myLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                Get_WMS_InWarehouseTaskQuantity();
            }
        }, 1500);
    }

    private void Get_WMS_InWarehouseTaskQuantity() {
        HttpClient.getInstance().getData(CommonHttpConsts.Get_WMS_InWarehouseTaskQuantity, "Get_WMS_InWarehouseTaskQuantity").headers("token", SPUtils.get(mContext, "token", "") + "").params("u_id", SPUtils.get(mContext, "U_Id", "") + "").params("r_id", SPUtils.get(mContext, "R_ID", "") + "")//角色名
                .params("wh", U_DEPOT_ID).execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 && !StringUtils.isEmpty(info)) {
                            Map dataMap = JSON.parseObject(info, Map.class);
                            if (!dataMap.isEmpty()) {
                                setDataView2(dataMap);
                            }
                        } else {
                            ToastUtil.show(msg);
                        }
                    }
                });
    }

    private void Get_WMS_HomeStatistics() {
        HttpClient.getInstance().getData(CommonHttpConsts.Get_WMS_HomeStatistics, "Get_WMS_HomeStatistics").headers("token", SPUtils.get(mContext, "token", "") + "").params("u_id", SPUtils.get(mContext, "U_Id", "") + "").params("r_id", SPUtils.get(mContext, "R_ID", "") + "")//角色名
                .params("wh", U_DEPOT_ID).execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 && !StringUtils.isEmpty(info)) {
                            Map dataMap = JSON.parseObject(info, Map.class);
                            if (!dataMap.isEmpty()) {
                                setDataView(dataMap);
                            }
                        } else if (code == 1002) {
                            get_WMS_RefreshToken();
                        } else {
                            ToastUtil.show(msg);
                        }
                    }
                });
    }

    private void get_WMS_RefreshToken() {
        HttpClient.getInstance().getData(CommonHttpConsts.get_WMS_RefreshToken, "get_WMS_RefreshToken")
                .params("token", SPUtils.get(mContext, "token", "") + "")
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 && !StringUtils.isEmpty(info)) {
                            SPUtils.put(mContext, "token", info);//token码

                            Get_WMS_HomeStatistics();
                            new Handler(Looper.myLooper()).postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Get_WMS_InWarehouseTaskQuantity();
                                }
                            }, 1500);
                        } else {
                            ToastUtil.show(msg);
                        }
                    }
                });
    }

    public void initView(View view) {
        moduleBeans = new ArrayList<>();
        viewFlipper = view.findViewById(R.id.viewFlipper);
        lyChu = view.findViewById(R.id.lyChu);
        lyQuest = view.findViewById(R.id.lyQuest);
        tvChuNum = view.findViewById(R.id.tvChuNum);
        lyRecords = view.findViewById(R.id.lyRecords);
        tvOutNum = view.findViewById(R.id.tvOutNum);
        tvQuestNum = view.findViewById(R.id.tvQuestNum);
        tvUserName = view.findViewById(R.id.tvUserName);
        tvchu = view.findViewById(R.id.tvchu);
        tvtask = view.findViewById(R.id.tvtask);
        tvdai = view.findViewById(R.id.tvdai);
        tvchu1 = view.findViewById(R.id.tvchu1);
        tvtask1 = view.findViewById(R.id.tvtask1);
        tvdai1 = view.findViewById(R.id.tvdai1);
        moduleBeans = (ArrayList<Map>) JSON.parseArray(SPUtils.get(mContext, "fun", "") + "", Map.class);
        lyChu.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            Intent intent = new Intent(mContext, RecognizeActivity.class);
            intent.putExtra("name", getResources().getString(R.string.chuku));
            intent.putExtra("type", 1);
            startActivity(intent);
        });
        lyQuest.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            Intent intent = new Intent(mContext, QuestActivity.class);
            intent.putExtra("name", getResources().getString(R.string.quest));
            intent.putExtra("type", 2);
            startActivity(intent);
        });
        lyRecords.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            Intent intent = new Intent(mContext, RecognizeActivity.class);
            intent.putExtra("name", getResources().getString(R.string.records));
            intent.putExtra("type", 3);
            startActivity(intent);
        });
        tvUserName.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            dismiss();
            initPopupWindow(tvUserName, stateList);
        });

        recyclerModule = view.findViewById(R.id.recyclerModule);
        recyclerModule.setLayoutManager(new LinearLayoutManager(mContext));
        moduleAdapter = new ModuleAdapter(mContext, moduleBeans);
        recyclerModule.setAdapter(moduleAdapter);
        moduleAdapter.setItemClickListener((position, mList) -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            LogUtils.e("TAG", "mList:" + mList.toString());
            String iv = mList.get("R_Fun_Id") + "";
            // 44A5331745AB49C397B40A3EDE3878C8  任务列表
            // B1F899F99775440786274DAF435AA351  出库单列表
            // CB1CB0F92DAC4CDAB7BC7C778DF6A674  出库记录
            Intent intent = null;
            if (iv.equals("44A5331745AB49C397B40A3EDE3878C8")) {
                intent = new Intent(mContext, QuestActivity.class);
            } else if (iv.equals("B1F899F99775440786274DAF435AA351")) {
                intent = new Intent(mContext, RecognizeActivity.class);
                intent.putExtra("type", 1);
            } else if (iv.equals("CB1CB0F92DAC4CDAB7BC7C778DF6A674")) {
                intent = new Intent(mContext, OutActivity.class);
                intent.putExtra("type", 3);
            } else if (iv.equals("309F223DF50448A0B9C6A20303639680")) {
                //入库单
                intent = new Intent(mContext, InspectionActivity.class);
                intent.putExtra("type", 4);
            } else if (iv.equals("2A6ECA5DC4224939B03E9BA5BE1BAFED")) {
                //我的任务
                intent = new Intent(mContext, TaskActivity.class);
                intent.putExtra("type", 5);
            } else if (iv.equals("89A98BB956E24B6D90F2E261B38B9870")) {
                //入库记录
                intent = new Intent(mContext, EnterActivity.class);
                intent.putExtra("type", 6);
            }
            if (intent == null) return;
            intent.putExtra("name", mList.get("R_Fun_Name") + "");
            startActivityForResult(intent, 1001);
        });
        moduleAdapter.setData(moduleBeans);
        initData();

        // 初始化手势检测器
        detectorCompat = new GestureDetectorCompat(mContext, new MyGestureListener());
        // 为ViewFlipper设置触摸监听
        viewFlipper.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detectorCompat.onTouchEvent(event);
                return true;
            }
        });

        // 设置初始动画
        setupAnimations();
    }

    private void setupAnimations() {
        // 设置进入和退出动画
        viewFlipper.setInAnimation(mContext, android.R.anim.fade_in);
        viewFlipper.setOutAnimation(mContext, android.R.anim.fade_out);
    }

    // 显示下一页（向左滑动）
    private void showNextView() {
        if (viewFlipper.getDisplayedChild() < viewFlipper.getChildCount() - 1) {
            viewFlipper.setInAnimation(mContext, R.anim.slide_in_left);
            viewFlipper.setOutAnimation(mContext, R.anim.slide_out_right);
            viewFlipper.showNext();
        }
    }

    // 显示上一页（向右滑动）
    private void showPreviousView() {
        if (viewFlipper.getDisplayedChild() > 0) {
            viewFlipper.setInAnimation(mContext, R.anim.slide_in_left); // 自定义动画
            viewFlipper.setOutAnimation(mContext, R.anim.slide_out_left);// 自定义动画
            viewFlipper.showPrevious();
        }
    }

    private PopupWindow popupWindow;
    private ArrayList<ChooseBean> stateList;

    private void initPopupWindow(View data, ArrayList<ChooseBean> popList) {
        View view = View.inflate(mContext, R.layout.layout_popup_hint, null);
        RecyclerView recyclerPop = view.findViewById(R.id.recyclerPop);
        recyclerPop.setLayoutManager(new LinearLayoutManager(mContext));
        SourceZAdapter sourceAdapter = new SourceZAdapter(mContext, popList);
        recyclerPop.setAdapter(sourceAdapter);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        view.setBackgroundColor(mContext.getResources().getColor(R.color.tv6060));
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        int[] location = new int[2];
        data.getLocationOnScreen(location);
        int xPos = location[0] + data.getWidth();
        int yPos = location[1] + data.getHeight() + 5;

        popupWindow.showAtLocation(data, Gravity.NO_GRAVITY, xPos, yPos);
        sourceAdapter.setOnItemClickListener((position, string) -> {
            tvUserName.setText(string.getName());
            stateList.get(0).setType(position);
            U_DEPOT_ID = string.getName();
            U_DEPOT_NAME = string.getUid();
            SPUtils.put(mContext, "isFIFO", string.isFIFO());
            SPUtils.put(mContext, "isVerification", string.isVerification());
            Get_WMS_HomeStatistics();
            new Handler(Looper.myLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    Get_WMS_InWarehouseTaskQuantity();
                }
            }, 1500);

            dismiss();
        });
    }

    private void dismiss() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    // 手势检测参数
    private final int SWIPE_THRESHOLD = 100;// 滑动距离阈值
    private final int SWIPE_VELOCITY_THRESHOLD = 100; // 滑动速度阈值

    class MyGestureListener extends SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                float diffX = e2.getX() - e1.getX();
                float diffY = e2.getY() - e1.getY();

                // 判断是否是水平滑动（X轴移动距离大于Y轴，且超过阈值）
                if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {

                    if (diffX > 0) {
                        // 向右滑动 - 显示上一页
                        showPreviousView();
                    } else {
                        // 向左滑动 - 显示下一页
                        showNextView();
                    }
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
    }
}